//
//  NoticeBarrageView.m
//  KingSelected
//
//  Created by 杨鹏 on 2023/11/3.
//

#import "NoticeBarrageView.h"
#import <MarqueeLabel.h>

@interface NoticeBarrageView ()<CAAnimationDelegate>

@property (nonatomic, strong) MarqueeLabel *contentLab;

@end

@implementation NoticeBarrageView

- (void)initViews {
    [self addSubview:self.contentLab];
}

- (void)setText:(NSString *)text {
    _text = text;
    self.contentLab.text = text;
    
    [self showAnima];
}

- (void)showAnima {
    CGFloat w = kWidthForScreen-36;
    
    CABasicAnimation *inAni = [CABasicAnimation animationWithKeyPath:@"position.x"];
    inAni.fromValue = @(kWidthForScreen + w / 2);
    inAni.toValue = @(w / 2 + 36);
    inAni.duration = 3;
    inAni.removedOnCompletion = NO;
    inAni.fillMode = kCAFillModeForwards;

    CABasicAnimation *outAni = [CABasicAnimation animationWithKeyPath:@"position.x"];
    outAni.fromValue = @(w / 2 + 36);
    outAni.toValue = @(-w / 2);
    outAni.duration = 3;
    outAni.beginTime = 6;
    outAni.removedOnCompletion = NO;
    outAni.fillMode = kCAFillModeForwards;
    
    NSArray *arr = @[inAni,outAni];
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = 9;
    group.delegate = self;
    group.animations = arr;
    [self.layer addAnimation:group forKey:nil];
}

- (MarqueeLabel *)contentLab {
    if (!_contentLab) {
        _contentLab = [[MarqueeLabel alloc] initWithFrame:CGRectMake(0, 0, kWidthForScreen-36, 28) duration:3 andFadeLength:3];
        _contentLab.textColor = kRGB(0x865C10);
        _contentLab.font = kFontRegula(12);
        [_contentLab setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
    }
    return _contentLab;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    [self removeFromSuperview];
    [_contentLab removeFromSuperview];
    _contentLab = nil;
    if (self.animateCompleteBlock) {
        self.animateCompleteBlock();
    }
}

@end
